use cpal::{
    traits::{DeviceTrait, HostTrait, StreamTrait},
    StreamConfig, SampleFormat, SupportedStreamConfig,
};
use hound::{WavSpec, WavWriter};
use std::sync::{Arc, Mutex};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 初始化音频主机
    let host = cpal::default_host();

    // 获取默认输入设备
    let input_device = host
        .default_input_device()
        .ok_or("No input device available")?;

    // 获取设备支持的配置范围
    let mut supported_configs = input_device.supported_input_configs()?;

    // 查找支持 16kHz 的配置（优先选择 f32 格式）
    let target_sample_rate = cpal::SampleRate(16000);
    let supported_config = supported_configs
        .find(|range| {
            range.min_sample_rate() <= target_sample_rate 
                && range.max_sample_rate() >= target_sample_rate
        })
        .ok_or("Device does not support 16kHz sample rate")?
        .with_sample_rate(target_sample_rate);

    // 构造最终的 StreamConfig（强制 16kHz）
    let config = StreamConfig {
        channels: supported_config.channels(),
        sample_rate: target_sample_rate,
        buffer_size: cpal::BufferSize::Default,
    };

    // 创建 WAV 文件（16kHz，16-bit）
    let spec = WavSpec {
        channels: supported_config.channels() as u16,
        sample_rate: target_sample_rate.0 as u32,
        bits_per_sample: 16,
        sample_format: hound::SampleFormat::Int,
    };
    let writer = Arc::new(Mutex::new(WavWriter::create("output_16k.wav", spec)?));

    // 启动音频流
    let writer_clone = writer.clone();
    let writer_finish = writer.clone();
    let stream = input_device.build_input_stream(
        &config,
        move |data: &[f32], _: &_| {
            let mut writer = writer_clone.lock().unwrap();
            for &sample in data {
                let sample_int16 = (sample * i16::MAX as f32) as i16;
                writer.write_sample(sample_int16).unwrap();
            }
        },
        |err| eprintln!("Audio stream error: {:?}", err),
        None,
    )?;

    stream.play()?;
    println!("Recording at 16kHz... Press Enter to stop.");
    std::io::stdin().read_line(&mut String::new())?;

    // 停止并保存
    drop(stream);
    let mut write= writer_finish.lock().unwrap();
    write.flush()?;
    println!("Saved to output_16k.wav");
    Ok(())
}